package cn.edu.ruc.cloudcomputing.book.time;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class TimeTest {

	/**
	 * 计算两个date之间的月份
	 * @param startDate 开始年月
	 * @param endDate 结束年月
	 * @return List 开始年月与结束年月之间的所有年月集合
	 */
	private List<String> getMonthsBetween(Date startDate,Date endDate){
		  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
		  String dateStr1 = sf.format(startDate)+"-01 00:00:00";
		  String dateStr2 = sf.format(endDate)+"-01 00:00:00";
		  Calendar c1 = Calendar.getInstance();
		  Calendar c2 = Calendar.getInstance();
		  //定义集合存放月份
		  List<String> list = new ArrayList<String>();
		  //添加第一个月，即开始时间
		  list.add(sf.format(startDate));
		  try {
			  // 开始日期
			  c1.setTime(sf.parse(dateStr1));
			  // 结束日期
			  c2.setTime(sf.parse(dateStr2));
		  } catch (ParseException e) {
			 e.printStackTrace();
		  }
		  while (c1.compareTo(c2) < 0) {
		   c1.add(Calendar.MONTH, 1);// 开始日期加一个月直到等于结束日期为止
		   Date ss = c1.getTime();
		   String str = sf.format(ss);
		   list.add(str);
		  }
		  return list;
	}
	
	/**
	 * 三者间的转换关系
	 * SimpleDateFormat <------>  Date   <---------> Calendar
	 * @param args
	 */
	public static void main(String[] args) {
		TimeTest test = new TimeTest();
		/**
		 * 模拟一
		 * 年份设置是从1900年开始,不建议使用
		 */
		/*Date startDate = new Date(2016-1900,5,6,12,12,12);
		Date endDate = new Date(2016-1900,9,27,12,12,12);
		List<String> listMonth = test.getMonthsBetween(startDate,endDate);*/
		/**
		 * 模拟二
		 */
		Calendar calendarT = Calendar.getInstance();
		System.out.println(calendarT.getTime());
		calendarT.set(2016, 4, 12, 1, 2, 32);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.set(2016, 9, 12, 1, 2, 32);
		Date dateStart = calendarT.getTime();
		Date dateEnd = calendar2.getTime();
		List<String> listMonth1 = test.getMonthsBetween(dateStart,dateEnd);
		System.out.println(listMonth1.toString());
	}
	
	
}
